import { parse } from 'querystring';
import moment from 'moment';
import request from '@/utils/request';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);


export const treeFind=(tree, func)=> {
  for (const data of tree) {
    if (func(data)) return data
    if (data.children) {
      const res = treeFind(data.children, func)
      if (res) return res
    }
  }
  return null
}

export const treeEnable=(tree:any,flag:any)=> {
  if(!tree){
    return;
  }
  if(tree&&!tree.length){
    tree.disabled=flag;
    if (tree.children) {
      treeEnable(tree.children,flag)
    }
    return;
  }

  for (const data of tree) {
    if (data.children) {
      treeEnable(data.children,flag)
    }
    data.disabled=flag;
  }
}

export const newUUID=()=>{
  var result: string;
  var i: string;
  var j: number;
  result = '';
  for (j = 0; j < 32; j++) {
      if (j == 8 || j == 12 || j == 16 || j == 20)
          result = result + '-';
      i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
      result = result + i;
  }
  let uuid= result.substr(0,24)+(new Date().getTime()+'').substr(0,12);
  return uuid
}

export const isImageType=(name:string)=>{
  return ['png', 'jpg','jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(name.toLowerCase()) !== -1
}

export const uniqueNameArray=(array:any[],key:string)=>{
  var nameMap:any = [];
  array.map((e:any)=>{
    if(e.numbs!=0&&e.is_gifts==0){
      nameMap.push(e[key])
    }
  })
  nameMap = nameMap.filter((e: any,i: any,self: string | any[])=>{
    return self.indexOf(e)==i
  })
  return nameMap;
}

export const getCurrentDate=()=>{
  return moment(Date.now()).format('YYYY-MM-DD')  
}

export const moneyFormat = (value:any)=>{ // 金额 格式化 
  if (!value && value !== 0) return '-';
  var intPart = Number(value) | 0; //获取整数部分
  var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); //将整数部分逢三一断

  var floatPart = '.00'; //预定义小数部分
  var value2Array = value.toString().split('.');
  //=2表示数据有小数位
  if (value2Array.length == 2) {
      floatPart = value2Array[1].toString(); //拿到小数部分

      if (floatPart.length == 1) { //补0,实际上用不着
          return intPartFormat + '.' + floatPart + '0';
      } else {  
          return intPartFormat + '.' + floatPart;
      }
  } else {
      return intPartFormat + floatPart;
  }
}

export const moneyFormat2 = (value:any)=>{ // 金额 格式化 
  if (!value||Number(value)===0) return '0.00';
  return '-'+moneyFormat(value)
}


export const exportFile=(url:string,fileName:string)=>{
  // let xhr = new XMLHttpRequest();
  // xhr.open(POST, url);
  // xhr.responseType = blob;
  // xhr.onload = () => {
  //   let ctx = xhr.response;
  //   let blob = new Blob([ctx]);
  //   if (msSaveOrOpenBlob in navigator) {//兼容IE
  //     window.navigator.msSaveOrOpenBlob(blob, fileName);
  //   } else {
  //     let aLink = document.createElement(a);
  //     aLink.download = fileName;
  //     aLink.style.display = none;
  //     aLink.href = URL.createObjectURL(blob);
  //     document.body.appendChild(aLink);
  //     aLink.click();
  //     document.body.removeChild(aLink);
  //   }
  // } ;
  // xhr.send();
  request(url, {
    method: 'GET',
    responseType: 'blob',
  }).then(res => {
    const blob = new Blob([res]);
    if ('msSaveOrOpenBlob' in navigator) {//兼容IE
      window.navigator.msSaveOrOpenBlob(blob, fileName);
    }else{
      const objectURL = URL.createObjectURL(blob);
      let btn = document.createElement('a');
      btn.download = fileName;
      btn.href = objectURL;
      btn.click();
      URL.revokeObjectURL(objectURL);
    }  
  });
}

export const  exportDirectFile=(url:string,fileName:string)=>{
  window.open(url);
}

export const manufacturerOption = ()=>{
  var data = JSON.parse(sessionStorage.getItem('factories') as string)
  var map:any = {}
  data.forEach((item:any) => {
      map[item.value] = {text:item.label}
  });
  return map
}

export const priceOption = ()=>{
  var data = JSON.parse(sessionStorage.getItem('prices') as string)
  var map:any = {}
  data.forEach((item:any) => {
      map[item.sort] = {text:item.name}
  });
  return map
}

export const manufacturerOptionOnly = ()=>{
  var data = JSON.parse(sessionStorage.getItem('factories') as string)
  var map:any = {}
  data.forEach((item:any) => {
    if(item.flag=='1'){
      map[item.value] = {text:item.label}
    }
  });
  return map
}


export const productMixOption=()=>{
  return {
    '取栓+出血':{text:'取栓+出血'},
    '通路':{text:'通路'},
    '狭窄':{text:'狭窄'}
  }
}

export const productPropertyOption=()=>{
  return {
    '经营产品':{text:'经营产品'},
    '经营产品-思脉德':{text:'经营产品-思脉德'},
    '生产产品':{text:'生产产品'},
  }
}

export const manufacturerOptionArray=()=>{
  return JSON.parse(sessionStorage.getItem('factories') as string).filter((item:any)=>item.flag=='1')
}

export const accAdd=(num1:number,num2:number)=>{
  var r1,r2,m;
  try{
      r1 = num1.toString().split('.')[1].length;
  }catch(e){
      r1 = 0;
  }
  try{
      r2=num2.toString().split(".")[1].length;
  }catch(e){
      r2=0;
  }
  m=Math.pow(10,Math.max(r1,r2));
  return Math.round(num1*m+num2*m)/m;
}

// 两个浮点数相减
export const accSub=(num1:number,num2:number)=>{
  var r1,r2,m;
  try{
      r1 = num1.toString().split('.')[1].length;
  }catch(e){
      r1 = 0;
  }
  try{
      r2=num2.toString().split(".")[1].length;
  }catch(e){
      r2=0;
  }
  m=Math.pow(10,Math.max(r1,r2));
  var n=(r1>=r2)?r1:r2;
  return Number((Math.round(num1*m-num2*m)/m).toFixed(n));
}

// 两个浮点数相除
export const accDiv=(num1:number,num2:number)=>{
  var t1,t2,r1,r2;
  try{
      t1 = num1.toString().split('.')[1].length;
  }catch(e){
      t1 = 0;
  }
  try{
      t2=num2.toString().split(".")[1].length;
  }catch(e){
      t2=0;
  }
  r1=Number(num1.toString().replace(".",""));
  r2=Number(num2.toString().replace(".",""));
  return (r1/r2)*Math.pow(10,t2-t1);
}

  // 两个浮点数相乘
  export const accMul=(num1:number,num2:number)=>{
  var m=0,s1=num1.toString(),s2=num2.toString(); 
try{m+=s1.split(".")[1].length}catch(e){};
try{m+=s2.split(".")[1].length}catch(e){};
return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
}

export const momentNow=()=>{
  return  moment()
}

export const priceLevelData = ()=>{
  return [
    {
        value: '1',
        label: 'A级',
    },
    {
        value: '2',
        label: 'B级',
    },{
      value: '5',
      label: 'A-H2级',
    }, {
      value: '4',
      label: 'B-H2级',
    }, {
      value: '6',
      label: 'C-H2级',
    }
    ]
}
